<?php

	// +----------------------------------------------------------------------
	// | 文档
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\cms;

	use app\model\cms\Category as CategoryModel;
	use app\model\cms\Pattern as PatternModel;
	use app\common\event\Base;
	use app\model\cms\Document as DocumentModel;
	use app\model\cms\Attribute as AttributeModel;
	use app\event\ucenter\Action;
	use QL\QueryList;
	use think\db\Where;
	use think\facade\Db;
	use think\Exception;
	use think\facade\Event;
	use yicmf\tools\HttpService;
	use app\model\ucenter\User as UserModel;

	class Document extends Base
	{


		public function evaluate($param, $user)
		{
			try {
				$doc = DocumentModel::where('id', $param['id'])->find();
				if (!$doc) {
					throw new Exception('文档不存在');
				}
				if ($param['evaluate'] == 1) {
					// 有用
					$doc['useful'] = $doc['useful'] + 1;
				} else {
					// 无用
					$doc['useless'] = $doc['useless'] + 1;
				}
				$doc->save();
				$data['code'] = 0;
				$data['data'] = $doc;
				$data['message'] = '表态成功';
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 获取文档分页列表.
		 * @param int $category_id 分类ID
		 * @param int $list_rows 每页数量
		 * @param string $order 排序规则
		 * @param int $status 状态
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/3 13:58
		 */
		public static function listsByTime($category_id, $list_rows = null, $order = 'create_time DESC', $status = 1)
		{
			try {
				$lists = DocumentModel::where(new Where(self::listMap($category_id, $status)))
					->where('start_time', ['=', null], ['<', time_format()], 'or')
					->where('deadline_time', ['=', null], ['>', time_format()], 'or')
					->order($order)->paginate($list_rows);
				$data['code'] = 0;
				$data['data'] = $lists;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 搜索列表
		 * @param        $keyword
		 * @param null $category_id
		 * @param string $order
		 * @return mixed
		 * @author 微尘 <yicmf@qq.com>
		 * @datetime: 2019/6/9 17:52
		 */
		public static function search($keyword, $category_id = null, $order = 'create_time DESC')
		{
			try {
				if (!empty($category_id)) {
					$map = self::mapCategory($category_id);
				}
				$map['status'] = 1;
				$lists = DocumentModel::where(new Where($map))
					->where('title|keywords', 'like', '%' . $keyword . '%')
					->where('pattern_id', 5)
					->where('create_time', '<', time_format())
					->order($order)->paginate(105, false, [
						'type' => 'app\cms\page\Document',
						'query' => [
							//                                'category_id' => $category_id
						]
					]);
				$data['code'] = 0;
				$data['data'] = $lists;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 获取文档分页列表.
		 * @param int $category_id 分类ID
		 * @param int $list_rows 每页数量
		 * @param string $order 排序规则
		 * @param int $status 状态
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/3 13:58
		 */
		public static function lists($category_id, $list_rows = 10, $order = 'create_time DESC', $is_recommend = null)
		{
			try {
				if ($is_recommend) {
					$lists = DocumentModel::with('cover')->
					where('status', 1)
						->where('pattern_id', 5)
						->where('is_recommend', 1)
						->where('create_time', '<', time_format())
//                        ->where('start_time', ['=', null], ['<', time_format()], 'or')
//                        ->where('deadline_time', ['=', null], ['>', time_format()], 'or')
						->order($order)->paginate($list_rows, false, [
							'type' => 'app\cms\page\Document',
							'query' => [
								//                                'category_id' => $category_id
							]
						]);
				} else {
					$lists = DocumentModel::with('cover')->where(new Where(self::mapCategory($category_id)))
						->where('status', 1)
						->where('create_time', '<', time_format())
//                        ->where('start_time', ['=', null], ['<', time_format()], 'or')
//                        ->where('deadline_time', ['=', null], ['>', time_format()], 'or')
						->order($order)->paginate($list_rows, false, [
							'type' => 'app\cms\page\Document',
							'query' => [
								//                                'category_id' => $category_id
							]
						]);
				}
				$data['code'] = 0;
				$data['data'] = $lists;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 获取指定文档的段落总数.
		 * @param number $id 段落ID
		 * @return number 总数
		 */
		public function partCount($id)
		{
			$map = ['status' => 1, 'pid' => $id, 'type' => 3];
			return $this->where($map)->count('id');
		}

		protected static function mapCategory($category_id, $child = true)
		{
			if ($child) {
				if (is_array($category_id)) {
					$category_ids = $category_id;
				} else {
					$category_ids = CategoryModel::where('pid', $category_id)->where('status', 1)->column('id');
					if ($category_ids) {
						$category_ids[] = $category_id;
					} else {
						$category_ids = $category_id;
					}
				}
				$map['category_id'] = ['in', $category_ids];
			} else {
				$map['category_id'] = $category_id;
			}
			return $map;
		}

		/**
		 * 设置where查询条件.
		 * @param number $category_id 分类ID
		 * @param number $pos 推荐位
		 * @param int $status 状态
		 * @return array 查询条件
		 */
		private static function listMap($category_id, $status = 1, $pos = null)
		{
			/* 设置状态 */
			$map = ['status' => $status];
			/* 设置分类 */
			if (!empty($category_id)) {
				if (is_numeric($category_id)) {
					$map['category_id'] = $category_id;
				} else {
					$map['category_id'] = ['in', $category_id];
				}
			}
			$map['create_time'] = ['<', time_format()];
			/* 设置推荐位 */
			if (is_numeric($pos)) {
				$map[] = "position & {$pos} = {$pos}";
			}
			return $map;
		}

		/**
		 * 完善信息
		 * @param      $param
		 * @param null $user
		 * @author 微尘 <yicmf@qq.com>
		 * @datetime: 2019/6/14 15:23
		 */
		public function perfect($param, $user = null)
		{
			try {
				Db::startTrans();
				$document = DocumentModel::where('id', $param['id'])->where('user_id', $user['id'])->find();
				if (!$document) {
					throw new Exception('素材不存在');
				}
				if (empty($document['cover_id'])) {
					throw new Exception('请补充封面');
				}
				if (empty($document['photo'])) {
					throw new Exception('请补充附件');
				}
				if (check_badword($param['title'])) {
					throw new Exception('关键词存在屏蔽词汇');
				}
				//                if (check_badword($param['keywords']))
				//                {
				//                    throw new Exception('关键词存在屏蔽词汇');
				//                }
				if (!$param['category_id']) {
					throw new Exception('请选择分类');
				}
				//                if (!trim($param['keywords']))
				//                {
				//                    throw new Exception('请填写关键词');
				//                }
				$cate = CategoryModel::where('status', 1)->where('id', $param['category_id'])->find();
				if (!$cate || !$cate['pid']) {
					throw new Exception('分类不合法');
				}
				$document['title'] = $param['title'];
				$document['category_id'] = $param['category_id'];
				$document['is_original'] = $param['is_original'];
				//                $document['keywords'] = $param['keywords'];
				//                $document['zhen'] = $param['zhen'];
				$document['coin'] = $param['coin'];
				$document['is_perfect'] = 1;
				$document['status'] = 0;
				$document->save();
				$document['photo']['ext'] = $param['ext'];
				$document['photo']['ext'] = $param['ext'];
				$document['photo']['height'] = $param['height'];
				$document['photo']['width'] = $param['width'];
				$document['photo']['zhen'] = $param['zhen'];
				$document->photo->save();
				Db::commit();
				$data['code'] = 0;
				$data['message'] = '提交成功';
			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}


		public function delete($param, $user = null)
		{
			// 删除素材
			$result = DocumentModel::where('user_id', $user['id'])->where('id', $param['id'])->find();
			if ($result) {
				$result['status'] = -2;
				$result->save();
			}
			$data['code'] = 0;
			return $data;
		}

		/**
		 * 更新文档内容
		 * @param array $param
		 * @param UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/3 6:37
		 */
		public function update($param, $user = null)
		{
			try {
				if (empty($param['id'])) {
					// 新增
					/* 扩展内容 */
					$name = PatternModel::where('id', $param['pattern_id'])->value('name');
					if (!$name) {
						throw new Exception('数据格式不完整');
					}
					if ($user) {
						$param['user_id'] = $user['id'];
					}
					$param['status'] = 1;
					Db::startTrans();
					//新增基础文档
					$document = DocumentModel::create($param);
					// 获取字段
					$attribute_fields = AttributeModel::where('pattern_id', $param['pattern_id'])->column('name');
					$model_save = [];
					foreach ($attribute_fields as $value) {
						if (isset($param[$value])) {
							$model_save[$value] = $param[$value];
						};
						if (isset($param[$name][$value])) {
							$model_save[$value] = $param[$name][$value];
						};
					}
					if (!$document->$name()->save($model_save)) {
						//删除基础数据
						throw new Exception('关联模型保存失败');
					}
					//行为记录
					Action::log('document_add', $document);
					// 注册内容添加完成钩子
					Event::trigger('document_add_complete', $document);
					$data['message'] = '新增成功';
				} else {
					// 修改
					$document = DocumentModel::find($param['id']);
					if (!$document) {//数据异常
						throw new Exception('数据不存在');
					}
					/* 更新扩展内容 */
					$name = PatternModel::where('id', $document['pattern_id'])->value('name');
					if (!$name) {
						throw new Exception('数据格式不完整');
					}
					$model = $document->$name;
					//基础文档信息保存
					unset($param['id']);
					$base_result = $document->save($param);
					//                    dump($model);
					// 获取字段
					$one_fields = AttributeModel::where('pattern_id', $document['pattern_id'])->column('name');
					if (!$one_fields) {
						throw new Exception('数据格式不完整');
					}
					foreach ($one_fields as $value) {
						if (isset($param[$value])) {
							$model[$value] = $param[$value];
						};
						if (isset($param[$name][$value])) {
							$model[$value] = $param[$name][$value];
						}
					}
					$extend = $model->save();
					if (!($base_result || $extend)) {
						throw new Exception('数据保存异常');
					}
					Action::log('document_update', $document);
					$data['message'] = '更新成功';
				}
				Db::commit();
				// 返回数据
				$data['code'] = 0;
				$data['data'] = $document;
			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 查询文档详情
		 * @param array $param
		 * @param UserModel|null $user
		 * @param bool $read
		 * @return mixed
		 * @author 微尘 <yicmf@qq.com>
		 * @datetime: 2020/8/19 8:05
		 */
		public function detail($param, $user = null, $read = false)
		{
			try {
				/* 获取基础数据 */
				$map[] = ['status', '>', -1];
				if (isset($param['id']) && is_numeric($param['id'])) {
					$map[] = ['id', '=', $param['id']];
				}elseif (isset($param['id']) && !is_numeric($param['id'])) {
					$map[] = ['name', '=', $param['id']];
				} elseif (isset($param['name'])) {
					$map[] = ['name', '=', $param['name']];
				} else {
					throw new Exception('查询条件错误');
				}
				$document = DocumentModel::with('pattern')->where($map)->where('status', 1)->find();
				if (!$document) {
					throw new Exception('文档不存在');
				}
				if ($read) {
					$document->view++;
					$document->save();
				}
				$name = $document['pattern']['name'];
				$document->$name;
				$data['code'] = 0;
				$data['data'] = $document;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 返回前一篇文档信息.
		 * @param array $info 当前文档信息
		 * @return \think\Model|null
		 * @throws \thinkException
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/3 6:51
		 */
		public static function prev($info)
		{
			return DocumentModel::where('status', 1)->whereTime('create_time', '<', $info['create_time'])->where('category_id', $info['category_id'])->order('create_time DESC')->find();
		}

		/**
		 * 返回下一篇文档信息.
		 * @param array $info 当前文档信息
		 * @return \think\Model|null
		 * @throws \thinkException
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/3 6:51
		 */
		public static function next($info)
		{
			return DocumentModel::where('status', 1)->whereTime('create_time', '>', $info['create_time'])->where('category_id', $info['category_id'])->order('create_time ASC')->find();
		}

	}
